/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.config.MySQLQuery;
import model.pojo.ThamSoPOJO;
import model.pojo.TinhTrangPOJO;
import model.util.MySQLProviders;

/**
 *
 * @author QuocThanh
 */
public class ThamSoDAO {
   
   public static int laySoLuongTrenTrang() {
      int soLuong = -1;
      String sql = "select GiaTri  from thamso where tenthamso='soluongtrentrang'";
      MySQLProviders helper = new MySQLProviders();
      helper.open();
      ResultSet rs = helper.executeQuery(sql);
      try {
         if (rs.next()) {
            soLuong = rs.getInt("GiaTri");
         }
      } catch (SQLException ex) {
         System.out.println(ex.getMessage());
      }
      helper.close();
      return soLuong;
   }
   
   public static ArrayList<ThamSoPOJO> getDanhSachCoPhanTrang(int trang) throws FileNotFoundException, IOException {
      ArrayList<ThamSoPOJO> ds = new ArrayList<ThamSoPOJO>(); 
      int soSanPhamTrenTrang = ThamSoDAO.laySoLuongTrenTrang();
      int batDau = (trang - 1) * soSanPhamTrenTrang;
      if(soSanPhamTrenTrang==batDau)
          batDau=1;     
      //mo ket noi
      MySQLProviders helper = new MySQLProviders();
      helper.open();
      
      //doc query tu file text
      //lay cau truy van tu file text
     MySQLQuery mySQLQuery=new MySQLQuery();
     mySQLQuery.Read("PHANTRANG");
     String sql=String.format(mySQLQuery.GetQuery(MySQLQuery.QueryKey.SELECT_ALL_THAMSO_PHANTRANG),batDau,soSanPhamTrenTrang);
      ResultSet rs = helper.executeQuery(sql);
      try {
         while (rs.next()) {
            ThamSoPOJO temp = new ThamSoPOJO();
            temp.setTenThamSo(rs.getString("TenThamSo"));
            temp.setGiaTri(rs.getInt("GiaTri"));
            ds.add(temp);
         }
      } catch (SQLException ex) {
         System.out.println(ex.getMessage());
      }
      helper.close();
      return ds;
   }
   
    public static ThamSoPOJO getById(String id){
       ThamSoPOJO obj=new ThamSoPOJO();
       MySQLProviders helper = new MySQLProviders();
       helper.open();
       ResultSet rs = helper.executeQuery("select *from thamso where tenthamso='"+id+"'");
       try {
           while (rs.next()) {            
            obj.setTenThamSo(rs.getString("TenThamSo"));
            obj.setGiaTri(rs.getInt("GiaTri"));
            
         }
       }catch(Exception e){
           
       }finally{
           helper.close();
       }
       return obj;
   }
}
